package test.n00000;

public class Problem00060 {
    public static void main(String[] args) {
        // PAYPALISHIRING
        // PAHNAPLSIIGYIR
        println("PAYPALISHIRING", 3);
        println("A", 1);
        // println("0123456789abcd", 3);
    }

    public static void println(String s, int numRows) {
        Solution ss = new Solution();
        System.out.println(s + "," + ss.convert(s, numRows));
    }

    public static class Solution {

        /**
         * Z 字形变换
         *
         * @param s
         * @param numRows
         * @return
         */
        public String convert(String s, int numRows) {
            int len = s.length();
            if (numRows == 1 || numRows >= len) {
                return s;
            }

            // Z 字形变换的周期 t=r+r-2=2r-2t=r+r−2=2r−2
            int t = 2 * numRows - 2;
            int c = (len + t - 1) / t * (numRows - 1);
            char[][] chars = new char[numRows][s.length()];

            int x = 0, y = -1;
            for (int i = 0; i < len; i++) {
                if (x % (numRows - 1) == 0 && y < numRows - 1) {
                    y++;
                } else {
                    y--;
                    x++;
                }
                chars[y][x] = s.charAt(i);
            }

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < numRows; i++) {
                for (int j = 0; j < len; j++) {
                    if (chars[i][j] != 0) {
                        sb.append(chars[i][j]);
                    }
                }
            }

            return sb.toString();
        }
    }
}
